<?php
/**
 * Created by PhpStorm.
 * User: KOOO
 * Date: 2017/11/29
 * Time: 14:41
 */

namespace App\Model;

use Core\Component\Di;
use Swoole\Table;


class Putter
{
    static function put() {
        $len = Queue::length();
        if($len < 3000) {
            $db = Di::getInstance()->get('MYSQL');
            $db->where ("stats", 1)->where ("lock_status", 0);

            $timerList = $db->get(TABLE_NAME, null, '*');
            foreach ($timerList as $task) {
                if (empty($task['lastupdate'])) {
                    $lastupdate = 0;
                } else {
                    $lastupdate = strtotime($task['lastupdate']);
                }
                $run = false;
                if($task['dotime_step']) {
                    if (time() - $lastupdate >= $task['dotime_step']) {
                        Queue::set($task['tid']);
                        $run = true;
                    }
                } else {
                    $currentTime = strtotime(date('Y-m-d', time())." ".$task['dotime']);
                    if(time() > $currentTime && $lastupdate < $currentTime) {
                        Queue::set($task['tid']);
                        $run = true;
                    }
                }

                if ($run == false && $task['runtimes'] > 1) {
                    Queue::set($task['tid']);
                }
            }
        }
    }

    static function unlock() {
        $db = Di::getInstance()->get('MYSQL');
        $db->where ("stats", 1)->where ("lock_status", 1);

        $lockList = $db->get(TABLE_NAME, null, 'tid,lastupdate');


        $update_db = Di::getInstance()->get('MYSQL');
        foreach ($lockList as $list) {
            if($list['lastupdate'] == null) {
                $lastupdate = 0;
            } else {
                $lastupdate = strtotime($list['lastupdate']);
            }
            if(time() - $lastupdate >= 120) {
                $update_db->where('tid', $list['tid']);
                $update_db->update(TABLE_NAME, ['lock_status'=>0]);
            }
        }
    }
}